package com.thread.DeadLock;

import java.util.concurrent.locks.ReentrantLock;

/*测试Lock
案例：买口罩
1、锁只能保证资源操作的安全性，不能保证每个线程都能从CUP得到线程执行
2、sleep方法让线程执行后等待，让其他线程有机会执行
 */
public class TestLock {
    public static void main(String[] args) {
        //同时启动多个线程，操作资源是不安全的,为了安全，引入Lock
        BuyMask buyMask = new BuyMask();
        new Thread(buyMask,"USA").start();
        new Thread(buyMask,"UK").start();
        new Thread(buyMask,"CANAD").start();


    }
}

class BuyMask implements Runnable{
    int maskNum = 10;
    //用可重入锁，定义LOCK
     private final ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true){
            lock.lock();//加锁
            try {
                if (maskNum > 0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "买到口罩" + maskNum--);
                } else {
                    break;
                }
            } finally {
                lock.unlock();//解锁
            }

        }
    }
}

